package com.yq.comm.command.impl;

import com.yq.comm.command.InitContextCommand;
import com.yq.comm.constant.ContextConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by yq on 16-8-14.
 */
public class FileUploadPathInitCommand  implements InitContextCommand{
    private static final Log log = LogFactory.getLog(FileUploadPathInitCommand.class);
    private static final String fileUploadPropertiesKey = "fileUploadPath";

    public FileUploadPathInitCommand() {
    }

    public void execute() {
        Properties properties = new Properties();
        InputStream inputStream = null;
        String configFilePath = "/file-upload.properties";
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFilePath);
            properties.load(inputStream);
        } catch (FileNotFoundException e) {
            log.error("Error occurs while init file upload path, file not fount for path:" + configFilePath, e);
            throw new RuntimeException(e);
        } catch (IOException ioe){
            log.error("Error occurs while load properties from file:" + configFilePath, ioe);
            throw new RuntimeException(ioe);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("Error closing file input stream for path:" + configFilePath, e);
                }
            }
        }
        String fileUploadPath = properties.getProperty(fileUploadPropertiesKey);
        String fileUploadFullPath = System.getProperty("web.root") + "/" + fileUploadPath;
        log.info("file upload path catch from file " + configFilePath + " is " + fileUploadPath + ", full path is " + fileUploadFullPath);
        ContextConstants.FILE_UPLOAD_PATH = fileUploadFullPath;
    }

    public void undo() {
        ContextConstants.FILE_UPLOAD_PATH = null;
    }
}
